<template>
    <!-- // 货物来源 -->
    <div class="page-container">
        <div class="in-container">
            <AppSearchForm @submit="search()" @reset="reset()">
                <el-form-item>
                    <el-select
                        v-model="query.yearDate"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="选择年份"
                        style="width: 200px">
                        <el-option
                            v-for="item in yearOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select
                        v-model="query.currency"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="输入币别搜索"
                        :remote-method="currencySelect"
                        :loading="selectLoading"
                        style="width: 200px">
                        <el-option
                            v-for="item in selectOptions"
                            :key="item.id"
                            :label="item.currencyCode"
                            :value="item.currencyCode" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="isIncome">
                    <el-select
                        v-model="query.isIncome"
                        placeholder="请选择收付"
                        clearable
                        style="width: 200px">
                        <el-option :label="'应收'" :value="'0'" />
                        <el-option :label="'应付'" :value="'1'" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="beginTime">
                    <el-date-picker
                        v-model="query.beginTime"
                        type="date"
                        style="width: 200px"
                        placeholder="起始时间"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item prop="endTime">
                    <el-date-picker
                        v-model="query.endTime"
                        type="date"
                        style="width: 200px"
                        placeholder="截止时间"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
            </AppSearchForm>
            <div class="btn-area">
                <el-button @click="openDialog" type="primary"> 新增 </el-button>
                <el-button @click="deleteSelectData" type="danger"> 删除 </el-button>
            </div>
            <AppPageTable
                stripe
                :data="tableData.data"
                @change="getList()"
                :autostyle="'height: calc(100% - 81px);'"
                :option="tableData.option">
                <el-table-column show-overflow-tooltip type="selection" width="40" fixed="left" />
                <el-table-column
                    :show-overflow-tooltip="true"
                    prop="currency"
                    width="80"
                    label="币种" />
                <el-table-column
                    :show-overflow-tooltip="true"
                    prop="isIncome"
                    width="80"
                    label="收付">
                    <template #default="scope">
                        {{ scope.row.isIncome == 0 ? '应付' : '应收' }}
                    </template>
                </el-table-column>
                <el-table-column
                    :show-overflow-tooltip="true"
                    prop="exchangeRate"
                    width="80"
                    label="汇率" />
                <el-table-column
                    :show-overflow-tooltip="true"
                    prop="beginTime"
                    width="150"
                    label="起始时间">
                    <template #default="scope">
                        {{
                            scope.row.beginTime
                                ? $utils.formatDateTime(scope.row.beginTime, 'YYYY-MM-DD')
                                : ''
                        }}
                    </template>
                </el-table-column>
                <el-table-column
                    :show-overflow-tooltip="true"
                    prop="endTime"
                    width="150"
                    label="截止时间">
                    <template #default="scope">
                        {{
                            scope.row.endTime
                                ? $utils.formatDateTime(scope.row.endTime, 'YYYY-MM-DD')
                                : ''
                        }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="scope">
                        <el-button @click.stop="update(scope.row)" type="primary">编辑</el-button>
                        <el-popconfirm
                            title="确定删除本条数据吗？"
                            @confirm="deleteData(scope.row)">
                            <template #reference>
                                <el-button type="danger">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </AppPageTable>
            <el-dialog :title="dialogData.title" v-model="dialogData.show" width="500px">
                <el-form :model="formData" :rules="formRules" label-width="80px" ref="form">
                    <el-form-item prop="currency" label="币别">
                        <el-select
                            v-model="formData.currency"
                            filterable
                            remote
                            reserve-keyword
                            placeholder="输入字符搜索"
                            :remote-method="currencySelect"
                            :loading="selectLoading"
                            style="width: 100%">
                            <el-option
                                v-for="item in selectOptions"
                                :key="item.id"
                                :label="item.currencyCode"
                                :value="item.currencyCode" />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="exchangeRate" label="汇率">
                        <el-input
                            v-model="formData.exchangeRate"
                            @input="
                                formData.exchangeRate = checkIsNumber(formData.exchangeRate)
                            "></el-input>
                    </el-form-item>
                    <el-form-item prop="isIncome" label="收付">
                        <el-radio-group v-model="formData.isIncome">
                            <el-radio :label="'1'">应收</el-radio>
                            <el-radio :label="'0'">应付</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item prop="timeArray" label="时间范围">
                        <el-date-picker
                            v-model="formData.timeArray"
                            type="daterange"
                            range-separator="-"
                            :clearable="false"
                            start-placeholder="起始时间"
                            end-placeholder="截止时间" />
                    </el-form-item>
                    <el-form-item prop="description" label="备注">
                        <el-input v-model="formData.description" type="textarea"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="cancel" link>取消</el-button>
                        <el-button type="primary" @click="submit"> 确认 </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { defineComponent } from 'vue'
import AppSearchForm from '@/components/AppSearchForm.vue'
import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import AppTitleBox from '@/components/AppTitleBox.vue'
import dayjs from 'dayjs'
import { ElMessageBox } from 'element-plus'
export default defineComponent({
    components: {
        AppSearchForm,
        AppPageTable,
        AppTitleBox,
    },
    data() {
        return {
            query: {
                currency: '',
                isIncome: '',
                timeArray: [],
                beginTime: '',
                endTime: '',
                yearDate: '',
            },
            tableData: {
                data: [],
                option: useTableOption(),
            },
            dialogData: {
                show: false,
                title: '',
                btnLoading: false,
            },
            formData: {
                currency: '',
                isIncome: '0',
                exchangeRate: '',
                timeArray: [],
                beginTime: '',
                endTime: '',
                description: '',
            },
            formRules: {
                currency: [{ required: true, message: '请选择币别', trigger: 'blur' }],
                exchangeRate: [{ required: true, message: '请输入汇率', trigger: 'blur' }],
                // beginTime: [{ required: true, message: "请选择时间", trigger: "blur" }],
                // endTime: [{ required: true, message: "请选择时间", trigger: "blur" }],
                timeArray: [
                    {
                        type: 'array',
                        required: true,
                        message: '请选择时间',
                        fields: {
                            // tpye类型试情况而定,所以如果返回的是date就改成date,如果返回的是string就改成string
                            0: { type: 'date', required: true, message: '请选择开始日期' },
                            1: { type: 'date', required: true, message: '请选择结束日期' },
                        },
                    },
                ],
            },
            selectOptions: [],
            yearOptions: [],
            selectLoading: false,
        }
    },
    methods: {
        checkIsNumber(e) {
            if (e == '00') {
                return '0'
            }
            let c = e.replace(/^\.+|[^\d.]/g, '')
            return c
        },

        getFiveYearsOptions() {
            for (let i = 0; i <= 4; i++) {
                let yearObj = {
                    label: dayjs().add(-i, 'year').format('YYYY'),
                    value: dayjs().add(-i, 'year').format('YYYY-MM-DD HH:mm:ss'),
                }
                this.yearOptions.push(yearObj)
            }
        },
        getList() {
            this.tableData.option.loading = true
            this.$http
                .get('/api/base/exchangerate/query', {
                    YearDate: this.query.yearDate,
                    Currency: this.query.currency,
                    IsIncome: this.query.isIncome,
                    BeginTime: this.query.beginTime,
                    EndTime: this.query.endTime,
                    PageIndex: this.tableData.option.page,
                    PageSize: this.tableData.option.pageSize,
                })
                .then((res) => {
                    res.content = res.content.map((item) => {
                        item.timeArray = [item.beginTime, item.endTime]
                        return item
                    })
                    this.tableData.data = res.content
                    this.tableData.option.total = res.totalElements
                })
                .finally(() => {
                    this.tableData.option.loading = false
                })
        },
        search() {
            this.tableData.option.page = 1
            this.tableData.pageSize = 10
            this.getList()
        },
        reset() {
            this.query.currency = ''
            this.query.isIncome = ''
            this.query.yearDate = ''
            this.query.timeArray = []
            this.tableData.option.page = 1
            this.tableData.pageSize = 10
            this.getList()
        },
        update(data) {
            this.formData = JSON.parse(JSON.stringify(data))
            this.dialogData.title = '编辑汇率'
            this.dialogData.show = true
        },
        deleteData(data) {
            this.$http
                .post('/api/base/exchangerate/delete', {
                    idArray: [data.id],
                })
                .then((res) => {
                    if (res.status) {
                        this.$message.success(res.message)
                        this.getList()
                    } else {
                        this.$message.error(res.message)
                    }
                })
        },
        openDialog() {
            this.dialogData.title = '新增汇率'
            this.dialogData.show = true
        },
        async submit() {
            this.dialogData.btnLoading = true
            let url = ''
            if (this.formData.id) {
                url = '/api/base/exchangerate/edit'
            } else {
                url = '/api/base/exchangerate/create'
            }
            await this.$refs.form.validate()
            this.$http.post(url, this.formData).then((res) => {
                if (res.status) {
                    this.$message.success(res.message)
                    this.getList()
                    this.dialogData.show = false
                } else {
                    this.$message.error(res.message)
                }
                this.dialogData.btnLoading = false
            })
        },
        cancel() {
            this.dialogData.show = false
        },
        currencySelect(query) {
            this.selectLoading = true
            this.$http
                .get('/api/base/currency/query', {
                    KeyWords: query,
                    PageIndex: 1,
                    PageSize: 50,
                })
                .then((res) => {
                    this.selectOptions = res.content
                })
                .finally(() => {
                    this.selectLoading = false
                })
        },
        spilDateFormData() {
            if (typeof this.formData.timeArray == 'object' && this.formData.timeArray.length > 0) {
                this.formData.beginTime = dayjs(this.formData.timeArray[0]).format('YYYY-MM-DD')
                this.formData.endTime = dayjs(this.formData.timeArray[1]).format('YYYY-MM-DD')
            } else {
                this.formData.beginTime = ''
                this.formData.endTime = ''
            }
        },
        spilQueryFormData() {
            if (typeof this.formData.timeArray == 'object' && this.query.timeArray.length > 0) {
                this.query.beginTime = dayjs(this.query.timeArray[0]).format('YYYY-MM-DD')
                this.query.endTime = dayjs(this.query.timeArray[1]).format('YYYY-MM-DD')
            } else {
                this.query.beginTime = ''
                this.query.endTime = ''
            }
        },
        /**
         * 多项删除业务
         */
        deleteSelectData() {
            let deleteSelectArray = []
            this.tableData.option.selected.forEach((t) => deleteSelectArray.push(t.id))
            ElMessageBox.confirm('确定删除所选信息', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    this.$http
                        .post('/api/base/exchangerate/delete', {
                            idArray: deleteSelectArray,
                        })
                        .then((res) => {
                            if (res.status) {
                                this.$message.success(res.message)
                                this.getList()
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                })
                .catch(() => {
                    this.$message.info('取消删除')
                })
        },
    },
    watch: {
        'dialogData.show'(newVal) {
            if (!newVal) {
                this.formData = {
                    currency: '',
                    isIncome: '0',
                    exchangeRate: '',
                    beginTime: '',
                    endTime: '',
                    description: '',
                }
                this.$nextTick(() => {
                    this.$refs.form.clearValidate()
                })
            }
        },
        'formData.timeArray': 'spilDateFormData',
        'query.timeArray': 'spilQueryFormData',
    },
    created() {
        this.getList()
        this.currencySelect('')
        this.getFiveYearsOptions()
    },
})
</script>

<style lang="scss" scoped>
.btn-area {
    margin-bottom: 8px;
}

:deep(.el-date-editor) {
    width: 100%;
}
</style>
